// pages/XLE/xle.js
import * as echarts from '../../ec-canvas/echarts.min';

import {
  lgRequest
} from '../../utils/ajax'
const app = getApp();

var radCtx; //定义canvas
var numCount = 4; //元素个数
var numSlot = 1; //一条线上的总节点数
var mW = 165; //Canvas的宽度
var mCenter = mW / 2; //中心点
var mAngle = Math.PI * 2 / numCount; //角度
var mRadius = mCenter - 45; //半径(减去的值用于给绘制的文本留空间)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    peopleInfo: {},
    nowork: [],
    okwork: [],
    userId: '',
    isButtomShow: false,
    chanelArray1: [
      ["完成总数", 80],
      ["未完成总数", 60],
      ["最大派单次数", 66],
      ["名下总站点数", 90],
    ],
    radarImg: '',
    sIndex:1
  },

  isTrue(e) {
    this.setData({
      isButtomShow: false,
      sIndex:e.currentTarget.dataset.index
    })
  },
  isFalse(e) {
    this.setData({
      isButtomShow: true,
      sIndex:e.currentTarget.dataset.index
    })
  },

  // 最大派单数
  getpaidan() {
    let userId1 = this.data.userId
    var that = this
    wx.request({
      url: `https://www.mengbaoonline.com:8182/server/workOther/Sum/${userId1}`,
      method: 'GET',
      dataType: 'json',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token'),
      },
      success: (res) => {
        that.data.chanelArray1[2][1] = res.data.data.all.sum
        // console.log(res.data.data.all.sum, '未完成工单111')
      },
    });
  },
  // 未完成工单
  getNowork() {
    let userId1 = this.data.userId
    var that = this
    wx.request({
      url: `https://www.mengbaoonline.com:8182/server/workOther/unWorkSite/${userId1}`,
      method: 'GET',
      dataType: 'json',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token'),
        // 'headerUserId': user.id,
        // 'headerUserToken': user.userToken
      },
      success: (res) => {
        that.data.chanelArray1[1][1] = res.data.data.length
        that.data.chanelArray1[3][1] = that.data.okwork.length + res.data.data.length
        // console.log(that.data.okwork,'length');
        console.log(res, '未完成工单')
        this.setData({
          nowork: res.data.data
        })
      },
    });
  },
  // 完成工单
  getOKWork() {
    let userId1 = this.data.userId
    wx.request({
      url: `https://www.mengbaoonline.com:8182/server/workOther/onWorkSite/${userId1}`,
      method: 'GET',
      dataType: 'json',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token'),
        // 'headerUserId': user.id,
        // 'headerUserToken': user.userToken
      },
      success: (res) => {
        var oldTimeArr = []
        var newTimeArr = []
        var xiaofu666 = []
        for (let index = 0; index < res.data.data.length; index++) {
          var oldTime = (res.data.data[index].createTime.slice(0, 4) * 365 * 30 * 24 * 60 * 60 + res.data.data[index].createTime.slice(5, 7) * 30 * 24 * 60 * 60 + res.data.data[index].createTime.slice(8, 11) * 24 * 60 * 60 + res.data.data[index].createTime.slice(11, 13) * 60 * 60 + res.data.data[index].createTime.slice(14, 16) * 60) * 1
          oldTimeArr = [...oldTimeArr, oldTime]
          var newTime = (res.data.data[index].overTime.slice(0, 4) * 365 * 30 * 24 * 60 * 60 + res.data.data[index].overTime.slice(5, 7) * 30 * 24 * 60 * 60 + res.data.data[index].overTime.slice(8, 11) * 24 * 60 * 60 + res.data.data[index].overTime.slice(11, 13) * 60 * 60 + res.data.data[index].overTime.slice(14, 16) * 60) * 1
          newTimeArr = [...newTimeArr, newTime]
          var xiaofu66 = (newTimeArr[index] - oldTimeArr[index]) / (365 * 30) * 3
          xiaofu666 = [...xiaofu666, xiaofu66]
          res.data.data[index].overTime = xiaofu666[index]
        }
        this.data.chanelArray1[0][1] = res.data.data.length
        console.log(res.data.data, 'res');
        var okWork = res.data.data.map((item) => {
          if (item.overTime / 24 > 1) {
            item.overTime = Math.trunc(item.overTime / 24) + '天'
          } else {
            item.overTime = Math.trunc(item.overTime) + '时'
          }
          // console.log(item.overTime/24>1);
          return item
        })
        // console.log(okWork,'okWork');
        this.setData({
          okwork: okWork
        })
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //页面加载时获取指定的canvas，加上this，指在当前的自定义组件内获取id为radarCanvas的dom元素
    // let ecComponent = this.selectComponent('#mychart-dom')
    radCtx = wx.createCanvasContext("radarCanvas", this)
    radCtx.save()
    radCtx.setFillStyle('#04112B')
    radCtx.fillRect(0, 0, 165, 180); //画出矩形白色背景
    radCtx.restore()
    //避免Android系统出现黑色背景
    this.setData({
      peopleInfo: JSON.parse(options.item),
      userId: JSON.parse(options.item).userId
    })
  },
  // 第一个图表

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    setTimeout(() => {
      this.getNowork()
    }, 100);
    this.getOKWork()
    this.getpaidan()
    setTimeout(() => {
      this.drawRadar()
    }, 500);
  },
  drawRadar: function () {
    var sourceData1 = this.data.chanelArray1
    wx.showLoading({
      title: '图形绘制中...',
    })
    // this.drawEdge() //画六边形,根据自己需要，可以是多边形或者圆形
    this.drawArcEdge() //画圆
    this.drawLinePoint() //绘制连接点
    this.drawRegion(sourceData1, '#FF6E13') //设置数据
    this.drawTextCans(sourceData1) //设置文本数据
    this.drawNumText(sourceData1) //设置文本数字数据
    // this.drawCircle(sourceData1, 'red') //设置节点
    //开始绘制
    setTimeout(() => {
      // radCtx.draw() //直接绘制
      radCtx.draw(false, setTimeout(() => {
        this.handleCanvarToImg()
      }, 500))
      //绘制完成后，将画布内容导出成指定大小的图片
    }, 1500)
  },

  // 绘制6条边
  drawEdge: function () {
    radCtx.setStrokeStyle("white")
    radCtx.setLineWidth(2) //设置线宽
    for (var i = 0; i < numSlot; i++) {
      //计算半径
      radCtx.beginPath()
      var rdius = mRadius / numSlot * (i + 1)
      //画6条线段
      for (var j = 0; j < numCount; j++) {
        //坐标
        var x = mCenter + rdius * Math.cos(mAngle * j);
        var y = mCenter + rdius * Math.sin(mAngle * j);
        radCtx.lineTo(x, y);
      }
      radCtx.closePath()
      radCtx.stroke()
    }
  },
  // 第一步：绘制圆，你可以通过修改numSlot的数的大小，来确定绘制几个圆
  drawArcEdge: function () {
    radCtx.setStrokeStyle("#FFD9C2") //设置线的颜色
    radCtx.setLineWidth(2) //设置线宽
    for (var i = 0; i < numSlot; i++) { //需要几个圆就重复几次
      // //计算半径
      radCtx.beginPath()
      var rdius = mRadius / numSlot * (i + 1) //计算每个圆的半径
      radCtx.arc(mCenter, mCenter, rdius, 0, 2 * Math.PI) //开始画圆
      radCtx.stroke()
    }
  },
  // 绘制连接点
  drawLinePoint: function () {
    radCtx.beginPath();
    for (var k = 0; k < numCount; k++) {
      var x = mCenter + mRadius * Math.cos(mAngle * k);
      var y = mCenter + mRadius * Math.sin(mAngle * k);

      radCtx.moveTo(mCenter, mCenter);
      radCtx.lineTo(x, y);
    }
    radCtx.closePath();
    radCtx.stroke();
  },
  //绘制数据区域(数据和填充颜色)
  drawRegion: function (mData, color) {
    radCtx.beginPath();
    for (var m = 0; m < numCount; m++) {
      var x = mCenter + mRadius * Math.cos(mAngle * m) * mData[m][1] / 100;
      var y = mCenter + mRadius * Math.sin(mAngle * m) * mData[m][1] / 100;

      radCtx.lineTo(x, y);
    }
    radCtx.closePath();
    radCtx.setFillStyle(color)
    radCtx.fill();
  },

  //绘制文字
  drawTextCans: function (mData) {
    radCtx.setFillStyle("#56FCFE")
    radCtx.setFontSize(10) //设置字体
    for (var n = 0; n < numCount; n++) {
      var x = mCenter + mRadius * Math.cos(mAngle * n);
      var y = mCenter + mRadius * Math.sin(mAngle * n);
      // radCtx.fillText(mData[n][0], x, y);
      //通过不同的位置，调整文本的显示位置
      if (n == 0) {
        radCtx.fillText(mData[n][0], x + 3, y + 10);
      } else if (n == 1) {
        radCtx.fillText(mData[n][0], x - 5, y + 30);
      } else if (n == 2) {
        radCtx.fillText(mData[n][0], x - 55, y + 25);
      } else if (n == 3) {
        radCtx.fillText(mData[n][0], x - 13, y - 5);
      } else if (n == 4) {
        radCtx.fillText(mData[n][0], x - 10, y - 10);
      }

    }
  },
  // 绘制数字
  drawNumText: function (mData) {
    radCtx.setFillStyle("red")
    radCtx.setFontSize(10) //设置字体
    for (var n = 0; n < numCount; n++) {
      var x = mCenter + mRadius * Math.cos(mAngle * n);
      var y = mCenter + mRadius * Math.sin(mAngle * n);
      if (n == 0) {
        radCtx.fillText(mData[n][1], x + 17, y - 8);
      } else if (n == 1) {
        radCtx.fillText(mData[n][1], x + 10, y + 15);
      } else if (n == 2) {
        radCtx.fillText(mData[n][1], x - 26, y + 5);
      } else if (n == 3) {
        radCtx.fillText(mData[n][1], x - 0, y - 15);
      } else if (n == 4) {
        radCtx.fillText(mData[n][1], x + 5, y - 25);
      }

    }
  },
  //画点
  drawCircle: function (mData, color) {
    var r = 3; //设置节点小圆点的半径
    for (var i = 0; i < numCount; i++) {
      var x = mCenter + mRadius * Math.cos(mAngle * i) * mData[i][1] / 100;
      var y = mCenter + mRadius * Math.sin(mAngle * i) * mData[i][1] / 100;

      radCtx.beginPath();
      radCtx.arc(x, y, r, 0, Math.PI * 2);
      radCtx.fillStyle = color;
      radCtx.fill();
    }
  },
  // 雷达图层级太高，转换为图片
  handleCanvarToImg() {
    var that = this
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 165,
      height: 180,
      destWidth: 495,
      destHeight: 540,
      fileType: 'jpg',
      quality: 1,
      canvasId: 'radarCanvas',
      success: function (res) {
        wx.hideLoading()
        // console.log('res', res)
        that.setData({
          radarImg: res.tempFilePath,
        });
      },
      complete: function (err) {
        wx.hideLoading()
        // console.log('err', err)
      }
    }, that);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

// console.log(res.data.data[0].createTime.slice(0,4),'年');
// console.log(res.data.data[0].createTime.slice(5,7)*30*24*60*60,'月');
// console.log(res.data.data[0].createTime.slice(8,11)*24*60*60,'天');
// console.log(res.data.data[0].createTime.slice(11,13)*60*60,'时');
// console.log(res.data.data[0].createTime.slice(14,16)*60,'分');
// console.log(res.data.data[0].createTime.slice(17,19),'秒');
// console.log(res.data.data[0].createTime, '@@@');
// console.log(res.data.data[0].overTime, '@@');